package cn.kgc.service.impl;

import cn.kgc.entities.Emp;
import cn.kgc.mapper.EmpMapper;
import cn.kgc.service.EmpService;
import cn.kgc.vo.EmpSearch;
import com.github.pagehelper.PageHelper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Resource
    private EmpMapper empMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Emp> testDelay() {
        List<Emp> list = null;
        // 从缓存读取数据，如果没有，查询数据库，并把数据设置到缓存
        // 缓存穿透: 双重锁验证
        list = (List<Emp>) redisTemplate.opsForValue().get("allEmps");
        if (null == list) {
            synchronized (this) {
                list = (List<Emp>) redisTemplate.opsForValue().get("allEmps");
                if (null == list) {
                    list = empMapper.selectAll();
                    redisTemplate.opsForValue().set("allEmps", list);
                    System.out.println("----> 查询数据库... ");
                } else {
                    System.out.println("----> 查询缓存...................synchronized ");
                }
            }
        } else {
            System.out.println("查询缓存。。。。。。。。");
        }
        return list;
    }

    @Override
    public List<Emp> getAllEmp() {
        return empMapper.selectAll();
    }

    @Override
    public Emp getEmpById(Integer id) {
        return empMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addEmp(Emp emp) {
        empMapper.insert(emp);
    }

    @Override
    public void updateEmp(Emp emp) {
        empMapper.updateByPrimaryKey(emp);
    }

    @Override
    public void deleteEmpById(Integer id) {
        System.out.println("--------id:"+id);
        empMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Emp> searchEmp(EmpSearch param) {
        //分页参数设置
        PageHelper.startPage(param.getPageNum(), param.getPageSize());

        // 利用通用mapper做自定义条件查询
        Example example = new Example(Emp.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(param.getName())) {
            criteria.andLike("name", "%" + param.getName() + "%");
        }
        if (null != param.getMinSal()) {
            criteria.andGreaterThanOrEqualTo("sal", param.getMinSal());
        }
        if (null != param.getMaxSal()) {
            criteria.andLessThanOrEqualTo("sal", param.getMaxSal());
        }
        example.setOrderByClause("id desc");
        List<Emp> list = empMapper.selectByExample(example);
        return list;
    }


}
